package com.zgscwjm.taobaphelper;

import android.app.KeyguardManager;
import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import com.google.gson.Gson;
import com.zgscwjm.taobaphelper.auto.updateCookie;
import com.zgscwjm.taobaphelper.data.AccountBean;
import com.zgscwjm.taobaphelper.exutils.MyBaseConfig;
import com.zgscwjm.taobaphelper.exutils.StringUtils;
import com.zgscwjm.taobaphelper.xp.DssnapshotManager;
import com.zgscwjm.taobaphelper.xp.FileManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetflowMissionService extends Service {

    public static String tag = "NetflowMissionService";

    public KeyguardManager.KeyguardLock keyguardLock; //原变量o,这是个啥。。
    public  KeyguardManager keyguardManager; //原变量n
    public PowerManager.WakeLock wakeLock; // 原变量q, 我也不知道这是啥；
    public static final String a = (v.a + "DSBase/fetchNetflowBuyer");
    public static boolean b=false;

    public NetflowMissionService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    public static void c(NetflowMissionService netflowMissionService) {
        netflowMissionService.keyguardLock.disableKeyguard();
        netflowMissionService.wakeLock.acquire();
        if (netflowMissionService.wakeLock != null) {
            netflowMissionService.wakeLock.release();
        }

    }

    //查找目录下是否有淘宝安装包
    public static boolean e() {
        File file = new File(FileManager.TBInstallPath);
        if (file.exists() && file.length() >= 20971520) {
            return true;
        }
        Log.e(tag, "has no new taobao!");
        return false;
    }

    //这个方法不知道是干嘛的，好像是自己杀死自己的
    public static void k() {
        String c = com.zgscwjm.taobaphelper.b.a.c("ps uiautomator");
        if (!StringUtils.isEmpty(c)) {
            String[] split = c.split("\\s+");
            if (split.length > 10) {
                c = split[9].trim();
                Log.e(tag, MyBaseConfig.Myappname + "kill pid" + c);
                com.zgscwjm.taobaphelper.b.a.c("kill" + c);

            }
        }
    }

    //更改系统设置文件的方法
    public static void l() {
        String str = "/data/data/com.android.providers.settings/databases/settings.db";
        if (!new File(str).exists()) {
            com.zgscwjm.taobaphelper.b.a.c(" touch " + str);
            com.zgscwjm.taobaphelper.b.a.c(" chown system:system " + str);
            com.zgscwjm.taobaphelper.b.a.c(" chmod 600 " + str);
        }
    }

    public final void a() {
        try {


            AccountBean readAccBean = FileManager.readAccBean();
            if (readAccBean == null) {
                readAccBean = new AccountBean();
            }
            String queryWangwangByXml;
            String readKey;
            String realname;
            if (new File(FileManager.tbUserInfoPath).exists()) {
                com.zgscwjm.taobaphelper.b.a.copy(FileManager.tbUserInfoPath, FileManager.localUserInfoPath);
                com.zgscwjm.taobaphelper.b.a.c(" chmod 777 /data/data/" + MyBaseConfig.Mypackagename + "/files/userinfo.xml");
                queryWangwangByXml = FileManager.queryWangwangByXml(FileManager.localUserInfoPath);
                Log.e(tag, "taobao user info:" + queryWangwangByXml);
                readKey = FileManager.readKey(getApplicationContext());
                if (!StringUtils.isEmpty(readAccBean.getRawusername())) {
                    readAccBean.decryptRealName(readKey);
                }

                realname = readAccBean.getRealname();
                if (StringUtils.isEmpty(queryWangwangByXml) || queryWangwangByXml.equals(realname)) {
                    Log.e(tag, "login wangwang is:" + queryWangwangByXml);
                    return;
                } else if (StringUtils.isEmpty(realname)) {
                    Log.e(tag, "acc wangwang is empty");
                    readAccBean.setRealname(queryWangwangByXml);
                    readAccBean.encryptRealNmae(readKey);
                    FileManager.writeContent(FileManager.accParamPath, new Gson().toJson(readAccBean));
                    return;
                } else {
                    Log.e(tag, "login wangwang is:" + realname + ", history wangwang :" + queryWangwangByXml);
                    if (realname.length() > 3) {
                        realname = realname.substring(0, 2);
                    }
                    if (queryWangwangByXml.startsWith(realname)) {
                        readAccBean.setRealname(queryWangwangByXml);
                        readAccBean.encryptRealNmae(readKey);
                        FileManager.writeContent(FileManager.accParamPath, new Gson().toJson(readAccBean));
                        return;
                    }
                    Log.e(tag, "acc wangwang is:" + realname);
                    return;
                }

            }
            Log.e(tag, "taobao user info xml not exist !!!");
            if (readAccBean == null) {
                try {
                    readAccBean = new AccountBean();

                } catch (Exception e) {
                    return;
                }
            }
            if (new File(FileManager.tbAliUserPath).exists()) {
                com.zgscwjm.taobaphelper.b.a.copy(FileManager.tbAliUserPath, FileManager.localAliuserPath);
                com.zgscwjm.taobaphelper.b.a.c(" chmod 777 /data/data/" + MyBaseConfig.Mypackagename + "/databases/aliuser");
                queryWangwangByXml = FileManager.readKey(getApplicationContext());
                readAccBean.decryptRealName(queryWangwangByXml);
                realname = readAccBean.getRealname();
                readKey = FileManager.queryWangwangByDatabase();
                if (StringUtils.isEmpty(readKey) || readKey.equals(realname)) {
                    Log.e(tag, "login wangwang is:" + readKey);
                    return;
                } else if (StringUtils.isEmpty(realname)) {

                    Log.e(tag, "acc wangwang is empty");
                    readAccBean.setRealname(readKey);
                    readAccBean.encryptRealNmae(queryWangwangByXml);
                    FileManager.writeContent(FileManager.accParamPath, new Gson().toJson(readAccBean));
                    return;
                } else {
                    Log.e(tag, "login wangwang is: " + realname + ", history wangwang: " + readKey);
                    if (realname.length() > 3) {
                        realname = realname.substring(0, 2);

                    }
                    if (readKey.startsWith(realname)) {
                        readAccBean.setRealname(readKey);
                        readAccBean.encryptRealNmae(queryWangwangByXml);
                        FileManager.writeContent(FileManager.accParamPath, new Gson().toJson(readAccBean));
                        return;
                    }
                    Log.e(tag, "acc wangwang is:" + realname);
                    return;
                }


            }
            Log.e(tag, "taobao aliuser db not exist");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public final  void b(){
        String bssid;
        String readContent;
        while (true)
        {
            boolean checkIsNeedBackUp=FileManager.checkIsNeedBackUp(getApplicationContext());
            if (!checkIsNeedBackUp)
            {
                updateCookie.sleep10000();
                updateCookie.sleep5000();
            }
            if (!b)
            {
                if (StringUtils.isEmpty(MainActivity.getVersionName(getApplicationContext(),MyBaseConfig.TBpacgename)))
                {
                    com.zgscwjm.taobaphelper.b.a.c(" pm uninstall com.taobao.taobao");
                    com.zgscwjm.taobaphelper.b.a.c(" pm install -r /data/local/tmp/taobao.apk");


                }
                FileManager.saveDBInfo(getApplicationContext(),FileManager.TaobaoVersionCode, String.valueOf(UpdateActivity.getVersioncode(getApplicationContext(), MyBaseConfig.Mypackagename)));
             if (this.keyguardManager.inKeyguardRestrictedInputMode())
             {
                 this.keyguardLock.disableKeyguard();
                 this.wakeLock.acquire();
                 if (this.wakeLock!=null)
                 {
                     this.wakeLock.release();
                 }
             }
             if (checkIsNeedBackUp && FileManager.readIfCanBackup())
             {
                 new Thread( new ac(this)).start();
                 return;
             }
             boolean readTBLogin=FileManager.readTBIsLogin(getApplicationContext());
                Log.e(tag,"check need login tb: "+ readTBLogin);
                if (!readTBLogin)
                {
                    new Thread(new ab(this)).start();
                    return;
                }
                else if (!checkIsNeedBackUp || FileManager.readFinishNum()<=0)
                {
                    bssid=((WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE)).getConnectionInfo().getBSSID();
                    readContent=FileManager.readContent(FileManager.bssidPath);
                    return;
                } else if (e())
                {
                    com.zgscwjm.taobaphelper.b.a.remove("/mnt/shell/emulated/0/UCDownloads/*");
                    com.zgscwjm.taobaphelper.b.a.remove("/mnt/shell/emulated/0/Pictures/taobao");
                    com.zgscwjm.taobaphelper.b.a.remove("/data/media/0/Pictures/taobao");
                    com.zgscwjm.taobaphelper.b.a.remove("/data/media/0/UCDownloads/*");
                    com.zgscwjm.taobaphelper.b.a.deletTaobao();
                     String readcontent2=FileManager.readContent(FileManager.userIdPath);
                    DssnapshotManager;// FIXME: 2017/3/16 写完这个类再继续写
                }

            }

        }
    }

    //请求的一个方法，暂时不知道请求啥，返回的是数据长度好像是。
    public static int a(String str, File file) {
        InputStream inputStream;
        FileOutputStream fileOutputStream;
        try {
            HttpURLConnection httpURLConnection1 = (HttpURLConnection) new URL(str).openConnection();
            httpURLConnection1.setRequestProperty("User-Agent", "PacificHttpClient");
            httpURLConnection1.setConnectTimeout(10000);
            httpURLConnection1.setReadTimeout(20000);
            if (httpURLConnection1.getResponseCode() == 404 || httpURLConnection1.getContentLength() < 29360128) {
                if (httpURLConnection1 != null) {
                    httpURLConnection1.disconnect();
                }
                return 0;
            } else {
                inputStream = httpURLConnection1.getInputStream();
                fileOutputStream = new FileOutputStream(file, false);
                byte[] barr = new byte[4096];
                int i = 0;
                while (true) {
                    int read = inputStream.read(barr);
                    if (read < 0) {
                        break;
                    }
                    fileOutputStream.write(barr, 0, read);
                    i += read;
                }
                if (httpURLConnection1 != null) {
                    httpURLConnection1.disconnect();

                }
                if (inputStream != null) {
                    inputStream.close();
                }
                fileOutputStream.close();
                return i;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
